/* Copyright (c) 2012 swing-on-fire Team
 * 
 * This file is part of Swing-On-Fire (http://code.google.com/p/swing-on-fire), licensed under the terms of the MIT
 * License (MIT).
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
package com.google.code.swingonfire.animation;

/**
 * A loop for animations. Executes the animation in sequential order.
 * 
 * @author ham
 */
public class AnimationLoop implements DurableAnimation
{

    /**
     * Creates an endless-loop using the specfied animations
     * 
     * @param animations the animations to loop
     * @return the animation
     */
    public static Animation loop(Animation... animations)
    {
        return loop(-1, animations);
    }

    /**
     * Creates a loop using the specified animations
     * 
     * @param loops the number of iterations, -1 for endless-loop
     * @param animations the animations to loop
     * @return the animation
     */
    public static Animation loop(int loops, Animation... animations)
    {
        return new AnimationLoop(loops, AnimationSequence.sequence(animations));
    }

    private final int loops;
    private final Animation animation;

    private int count;
    private boolean starting;
    private double startTime;
    private double duration = Double.NaN;

    /**
     * Creates a loop using the specified animations
     * 
     * @param loops the number of iterations, -1 for endless-loop
     * @param animations the animations to loop
     */
    protected AnimationLoop(int loops, Animation animation)
    {
        super();

        this.loops = loops;
        this.animation = animation;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double getDuration()
    {
        return duration;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void animationReset()
    {
        count = 0;
        starting = true;

        if (loops < 0)
        {
            duration = Double.NaN;
        }
        else
        {
            double currentDuration =
                (animation instanceof DurableAnimation) ? ((DurableAnimation) animation).getDuration() : Double.NaN;

            if (AnimationUtil.isUndefined(currentDuration))
            {
                duration = Double.NaN;
            }
            else
            {
                duration = currentDuration * loops;
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double animationStep(double delay, double time, double fraction)
    {
        if (starting)
        {
            starting = false;
            startTime = time;

            if (animation instanceof ResetableAnimation)
            {
                ((ResetableAnimation) animation).animationReset();
            }
        }

        time = time - startTime;

        double duration =
            (animation instanceof DurableAnimation) ? ((DurableAnimation) animation).getDuration() : Double.NaN;

        try
        {
            delay =
                AnimationUtil.animationResult(
                    animation.animationStep(delay, time, AnimationUtil.toFraction(time, duration)), time, duration);
        }
        catch (AnimationAbortedException e)
        {
            delay = Double.NaN;
        }
        catch (Exception e)
        {
            throw new AnimationRuntimeException(animation, "Invocation of animationStep caused exception", e);
        }

        if (AnimationUtil.isFinished(delay))
        {
            count += 1;
            starting = true;

            if ((loops < 0) || (count < loops))
            {
                delay = 0;
            }
        }

        return delay;
    }
}
